<?php

namespace App\Task;

use App\Model\Applet;
use App\Model\AppletCouponPromotionActivity;
use App\Model\AppletPlayletRel;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

class DyCheckActivityTask
{
    protected LoggerInterface $logger;

    public static $getTokenUrl = "https://open.douyin.com/oauth/client_token/";

    public static $checkUrl = "https://open.douyin.com/api/promotion/v2/activity/query_promotion_activity/";

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'dyCheckActivity');
    }

    public function execute()
    {
//        return;
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------开始定时获取营销活动状态');
        $this->logger->info('获取定时获取营销活动状态');
        //获取需要获取任务的视频
        $activityData = AppletCouponPromotionActivity::query()
            ->select(['applet_coupon_promotion_activity.id','activity_id','applet_id','app_id','app_secret'])
            ->leftJoin('applet','applet.id','=','applet_coupon_promotion_activity.applet_id')
//            ->where('applet_coupon_promotion_activity.status',1)
            ->get();
        if($activityData->isNotEmpty()){



            foreach ($activityData as $activityDatum){
                //查询关联表中的抖音小程序ID
                $this->logger->info('查询活动中中的抖音小程序ID,',[$activityDatum->applet_id]);
                //获取抖音token
                $accessToken = $this->getDyAccessToken($activityDatum->applet_id,$activityDatum->app_id,$activityDatum->app_secret);

                $checkResult = $this->checkPromotionActivity($accessToken,$activityDatum->activity_id);

                if(!empty($checkResult)) {
                    $this->logger->info('更新对应的营销活动',[$activityDatum->id]);
                    $activityDatum->status = $checkResult['promotion_activity']['status'];
                    $activityDatum->save();
                }
            }
        }else{
            $this->logger->info('没有营销活动状态数据');
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取营销活动状态数据');
    }
    public function getDyAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');

        $key = 'dy_admin_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'client_key'    => $app_id,
                'client_secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'POST');
            if (!empty($accessTokenInfo['data']['access_token'])){
                $accessToken = $accessTokenInfo['data']['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        $this->logger->info('抖音token为：'.$accessToken);
        return $accessToken;
    }

    public function checkPromotionActivity($accessToken,$activity_id){
        try {

//            sleep(1);
            $params = [
                'activity_id' => $activity_id,
            ];
            $checkUrl = self::$checkUrl;
            $this->logger->info('请求数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('请求Url：'.$checkUrl);
            //开始上传
            $checkResult  = $this->request($params, $checkUrl,'POST',$accessToken);
            if($checkResult['err_no'] == 0){
//                $this->logger->info('短请求营销活动成功 返回数据：'.PHP_EOL.var_export(['result' => $checkResult], true));
                return $checkResult;
            }else{
                $this->logger->error('请求营销活动数据失败 返回数据：'.PHP_EOL.var_export(['result' => $checkResult], true));
            }
            return false;
        }catch (\Exception $e){
            $this->logger->error('请求营销活动失败|错误：' . $e->getLine() . '|' . $e->getMessage());
            return false;
        }

    }
    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}